/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2019年01月01日
*   描    述：
*   
================================================================*/


#include <iostream>

using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if( !head || !head->next )
            return NULL;

        ListNode *slow = head;
        ListNode *fast = head;
        while( fast->next && fast->next->next ){
            slow = slow->next;
            fast = fast->next->next;
            if( slow == fast ){
                slow = head;
                while( slow != fast ){
                    slow = slow->next;
                    fast = fast->next;
                }
                
                return slow;
            }
        }
        
        return NULL;
    }
};
